package com.webserver.template_core;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.FileTemplateResolver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;

public class Creator {
    public static final File DataSourceDir = new File("./webapps/datasource");
    public static final File WebappsDir = new File("./webapps/myBlog");

    private TemplateEngine te;


//    public static void main(String[] args) {
//        Creator creator = new Creator();
//        creator.start();
//    }

    public Creator(){
        FileTemplateResolver tr = new FileTemplateResolver();
        tr.setTemplateMode("html");
        tr.setCharacterEncoding("utf-8");

        te = new TemplateEngine();
        te.setTemplateResolver(tr);
    }


    public void start(){
        DataSource ds = loadDataSource();

        createWebappDir();

        createIndexPage(ds);

        createSubject(ds);

        copyReourceFile();
    }

    private void copyReourceFile(){
        File[]subjectDirs = DataSourceDir.listFiles(f->f.isDirectory());
        for (File subjectDir:subjectDirs){
            File[]subs = subjectDir.listFiles(f->f.isFile()&&!f.getName().endsWith(".md"));

            File descDir = new File(WebappsDir,subjectDir.getName().split("_")[0]);

            for (File resource:subs){
                try (
                        FileInputStream fis = new FileInputStream(resource);
                        FileOutputStream fos = new FileOutputStream(new File(descDir,resource.getName()));
                ){
                    byte[]data = new byte[1024*10];
                    int len = 0 ;
                    while ((len=fis.read(data))!=-1){
                        fos.write(data,0,len);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    private void createSubject(DataSource ds){
        Set<Map.Entry<String,List<Article>>>set = ds.getDataSource().entrySet();
        for (Map.Entry<String,List<Article>> e:set){
            String []data = e.getKey().split("_");
            String pathName = data[0];
            String subjectName = data[1];
            File articleDir = new File(WebappsDir,pathName);
            if (!articleDir.exists()){
                articleDir.mkdirs();
            }

            List<Article>list = e.getValue();
            for (Article article:list){
                Context context = new Context();
                context.setVariable("datasource",ds);
                context.setVariable("article",article);

                File detail = new File(articleDir,article.getFileName());
                System.out.println("========================================="+article.getFileName());
                createHtml("./webapps/template/category/detail.html",context,detail);
            }
            Context context = new Context();
            context.setVariable("List",list);
            context.setVariable("subjectName",subjectName);
            context.setVariable("datasource",ds);
            File index = new File(articleDir,"index.html");
            createHtml("./webapps/template/category/index.html",context,index);
        }
    }

    private void createHtml(String template,Context context,File file){
        String html = te.process(template,context);

        try(FileOutputStream fos = new FileOutputStream(file)){
             fos.write(html.getBytes("utf-8"));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void createIndexPage(DataSource ds){
        Context context = new Context();
        context.setVariable("datasource",ds);

        File file = new File(WebappsDir,"index.html");
        createHtml("./webapps/template/index.html",context,file);
    }


    private void createWebappDir(){
        if (!WebappsDir.exists()){
            WebappsDir.mkdirs();
        }
    }

   public DataSource loadDataSource(){
       Map<String, List<Article>> map = new HashMap<>();
       File[] subjects = DataSourceDir.listFiles(f->f.isDirectory());

       for (File subject:subjects){
           File[] articleFiles = subject.listFiles(f->f.getName().endsWith(".md")&&
                   !f.getName().startsWith(".") &&!f.getName().startsWith("_"));
           Arrays.sort(articleFiles,(f1,f2)->f1.lastModified()>f2.lastModified()?-1:1);

           List<Article>list = new ArrayList<>();

           for (File articleFile:articleFiles){
               Article article = new Article(articleFile);
               list.add(article);
           }
           map.put(subject.getName(),list);
       }
       return new  DataSource(map);
   }
}
